package cameracontrol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

import event.MotionEvent;

import se.lth.cs.realtime.JThread;
import se.lth.cs.realtime.RTThread;

/**
 * MotionThread connects to MotionDetector on a Camera. Whenever a motion is
 * registered and sent by MotionDector, MotionThread updates the state of
 * MotionController by sending a message to its mailbox.
 */

public class MotionThread extends JThread {
	private Socket socket;
	private BufferedReader in;
	private MotionController motionControl;
	private boolean run = true;

	/**
	 * Constructs the class and connects to the MotionDetector server.
	 * 
	 * @param motionController
	 *            the control class for motions.
	 * @param ip
	 *            the ipadress of the MotionDetector
	 * @param port
	 *            the port of the MotionDetector
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public MotionThread(MotionController motionController, String ip, int port)
			throws UnknownHostException, IOException {
		socket = new Socket(ip, port);
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		this.motionControl = motionController;
	}

	/**
	 * Runs when this thread is started. Checks the message received from
	 * MotionDetector and sends an appropriate message to MotionController by
	 * using the motion method.
	 */
	@Override
	public void run() {
		while (run) {
			try {
				String s = in.readLine();
				if(s == null) {
					run = false;
					continue;
				}
				if (s.equals("MOTION"))
					motion(true);
				else if (s.equals("NOMOTION"))
					motion(false);
			} catch (IOException e) {
				
			}
		}
	}
	
	public void kill() {
		run = false;
		try {
			socket.close();
		} catch (IOException e) {
		}
		try {
			super.join();
		} catch (InterruptedException e) {
		}
	}

	private void motion(boolean motion) {
		motionControl.putEvent(new MotionEvent(motion, socket.getInetAddress().getHostName().toString()));
	}

}
